package com.emmp_ard.scancapture;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.emmp_ard.carplate.CarPlateDetection;
import com.emmp_ard.scan.camera.CameraManager;
import com.emmp_ard.scan.camera.FlashlightManager;
import com.emmp_ard.scan.decoding.CaptureActivityHandler;
import com.emmp_ard.scan.decoding.InactivityTimer;
import com.emmp_ard.scan.view.ViewfinderView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.StationDTO;
import com.huaxin.common.Entity.WaterIntakeDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.BigDeviceInfoActivity;
import com.huaxin.hxcloud.activity.HxStationSignInActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Vector;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Response;


public class ScanCaptureActivity extends BaseActivity implements Callback, SensorEventListener {


    @BindView(R.id.more)
    ImageView      more;
    @BindView(R.id.toolbar)
    Toolbar        toolbar;
    @BindView(R.id.preview_view)
    SurfaceView    previewView;
    @BindView(R.id.viewfinder_view)
    ViewfinderView viewfinderView;
    @BindView(R.id.txtResult)
    TextView       txtResult;
    @BindView(R.id.tishi_text)
    TextView       tishiText;
    @BindView(R.id.button_ligth)
    Button         buttonLigth;
    @BindView(R.id.button_input)
    Button         buttonInput;
    @BindView(R.id.button_back)
    Button         buttonBack;
    @BindView(R.id.erweima)
    TextView       erweima;
    @BindView(R.id.tiaoxingma)
    TextView       tiaoxingma;
    @BindView(R.id.selectlayout)
    LinearLayout   selectlayout;
    private String Tag = "ScanCaptureActivity";
    private CaptureActivityHandler handler;
    private boolean                hasSurface;
    private Vector<BarcodeFormat>  decodeFormats;
    private String                 characterSet;

    private InactivityTimer inactivityTimer;
    private MediaPlayer     mediaPlayer;
    private boolean         playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    // ----@phj-------
    private Boolean LigthOpen = false;

    public static String des;

    private SensorManager mSensorManager;
    private Sensor        mLightSensor;
    // ------------------
    public final static int TYPE_DEFAULT   = 0x00;
    public final static int TYPE_QR_CODE   = 0x01;
    public final static int TYPE_BAR_CODE  = 0x02;
    public final static int TYPE_PLATE_NUM = 0x03;

    public final static int MODE_DEFAULT      = 0x00;
    public final static int MODE_BIND_WATER   = 0x01;
    public final static int MODE_BIND_STATION = 0x02;
    public final static int MODE_BIND_CAR     = 0x03;
    int type = TYPE_DEFAULT;
    int mode = MODE_DEFAULT;
    private int extraId;


    public String getDes() {
        return des;
    }

    public void setDes(String des) {
        ScanCaptureActivity.des = des;
    }


    public static void start(Activity activity, int type, int mode, int extraId) {
        Intent intent = new Intent(activity, ScanCaptureActivity.class);
        intent.putExtra(Constants.IK_SWEEP_TYPE, type);
        intent.putExtra(Constants.IK_SWEEP_MODE, mode);
        intent.putExtra(Constants.IK_EXTRA, extraId);
        activity.startActivityForResult(intent, Constants.RET_SWEEP);
    }

    public static void start(Activity activity, int type, int mode) {
        Intent intent = new Intent(activity, ScanCaptureActivity.class);
        intent.putExtra(Constants.IK_SWEEP_TYPE, type);
        intent.putExtra(Constants.IK_SWEEP_MODE, mode);
        activity.startActivityForResult(intent, Constants.RET_SWEEP);
    }

    public static void start(Fragment fragment, int type, int mode, int extraId) {
        Intent intent = new Intent(fragment.getActivity(), ScanCaptureActivity.class);
        intent.putExtra(Constants.IK_SWEEP_TYPE, type);
        intent.putExtra(Constants.IK_SWEEP_MODE, mode);
        intent.putExtra(Constants.IK_EXTRA, extraId);
        fragment.startActivityForResult(intent, Constants.RET_SWEEP);
    }

    public static void start(Fragment fragment, int type, int mode) {
        Intent intent = new Intent(fragment.getActivity(), ScanCaptureActivity.class);
        intent.putExtra(Constants.IK_SWEEP_TYPE, type);
        intent.putExtra(Constants.IK_SWEEP_MODE, mode);
        fragment.startActivityForResult(intent, Constants.RET_SWEEP);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        type = extras.getInt(Constants.IK_SWEEP_TYPE, TYPE_DEFAULT);
        CarPlateDetection.TEST = type == 3;
        mode = extras.getInt(Constants.IK_SWEEP_MODE, MODE_DEFAULT);
        extraId = extras.getInt(Constants.IK_EXTRA, 0);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.scan_main;
    }

    @Override
    public void initView() {
        super.initView();
        CameraManager.init(getApplication());
        /*Modify for fix UI bug(http://192.168.0.18:3000/issues/12183) begin*/
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);// TYPE_GRAVITY

        setSupportActionBar(toolbar);
        toolbar.setTitle("扫一扫");
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

        buttonLigth.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (LigthOpen) {
                    FlashlightManager.disableFlashlight();
                    LigthOpen = false;
                    buttonLigth.setText("打开闪光灯");
                } else {
                    FlashlightManager.enableFlashlight();
                    LigthOpen = true;
                    buttonLigth.setText("关闭闪光灯");
                }

            }
        });

        erweima.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                des = "请扫描设备二维码";
                Drawable foucs, normal;
                Resources res = getResources();
                foucs = res.getDrawable(R.drawable.erweima_img_foucs);
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                foucs.setBounds(0, 0, foucs.getMinimumWidth(),
                        foucs.getMinimumHeight());
                normal = res.getDrawable(R.drawable.tiaoxingma_img_normal);
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                normal.setBounds(0, 0, normal.getMinimumWidth(),
                        normal.getMinimumHeight());
                erweima.setCompoundDrawables(null, foucs, null, null);
                tiaoxingma.setCompoundDrawables(null, normal, null, null);
                CameraManager.get()
                        .setScanMode(CameraManager.SCAN_MODEL.QRCODE);
                viewfinderView.postInvalidate();
            }
        });
        tiaoxingma.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                des = "请扫描水质化验条形码";
                Drawable foucs, normal;
                Resources res = getResources();
                foucs = res.getDrawable(R.drawable.tiaoxingma_img_foucs);
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                foucs.setBounds(0, 0, foucs.getMinimumWidth(),
                        foucs.getMinimumHeight());
                normal = res.getDrawable(R.drawable.erweima_img_normal);
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                normal.setBounds(0, 0, normal.getMinimumWidth(),
                        normal.getMinimumHeight());
                erweima.setCompoundDrawables(null, normal, null, null);
                tiaoxingma.setCompoundDrawables(null, foucs, null, null);
                CameraManager.get().setScanMode(
                        CameraManager.SCAN_MODEL.BARCODE);
                viewfinderView.postInvalidate();
            }
        });

        switch (type) {
            case TYPE_DEFAULT:
                des = "请扫描条形码或二维码";
                CameraManager.get().resetFramingRect();
                break;
            case TYPE_QR_CODE:
                erweima.performClick();
                break;
            case TYPE_BAR_CODE:
                tiaoxingma.performClick();
                break;
            case TYPE_PLATE_NUM:
                CarPlateDetection.sdpath = getIntent().getStringExtra("path");
                des = "请扫描车牌号";
                CameraManager.get().setScanMode(CameraManager.SCAN_MODEL.CARPLATE);
                selectlayout.setVisibility(View.INVISIBLE);
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mSensorManager != null) {
            mSensorManager.registerListener(this,
                    mLightSensor,
                    //mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    // 还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
                    // 根据不同应用，需要的反应速率不同，具体根据实际情况设定
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
        SurfaceHolder surfaceHolder = previewView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;
        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        // initBeepSound();
        vibrate = true;
    }

    @Override
    public void onPause() {

        if (mSensorManager != null) {
            mSensorManager.unregisterListener(this); // 销毁传感器事件
        }
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        Log.i("tanglu", "Calculated surfaceChanged;" + width + "," + height);
        CameraManager.get().setSurfaceSize(width, height);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }


    /**
     * 车牌识别的回调
     *
     * @param obj
     * @param barcode
     */
    public void handleDecode(String obj, Bitmap barcode) {
        inactivityTimer.onActivity();
        //        viewfinderView.drawResultBitmap(barcode);
        playBeepSoundAndVibrate();
        final String code = obj;
        if (mode == MODE_BIND_CAR) {
            bindCar(code);
        } else {
            txtResult.setText(obj + ":" + obj);
            Intent intent = new Intent();
            intent.putExtra("code", code);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    /**
     * 二维码条形码的回调
     *
     * @param obj     Json数据
     * @param barcode
     */
    public void handleDecode(Result obj, Bitmap barcode) {
        Log.e("lwjing", "二维码条形码的回调" + obj.toString());
        inactivityTimer.onActivity();
        //viewfinderView.drawResultBitmap(barcode);
        playBeepSoundAndVibrate();
        final String code = obj.getText();
        try {//json二维码解析
            JSONObject jsonObject = new JSONObject(code);
            String company = (String) jsonObject.get("HuaXinData");
            if ("HuaXinData".equals(company)) {
                String typeValue = (String) jsonObject.get("typeValue");
                switch (typeValue) { //个人名片
                    case "fre":
                        Intent intent = new Intent();
                        intent.putExtra("code", jsonObject.toString());
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                    case "dev":
                        String deviceCode = (String) jsonObject.get("deviceCode");
                        BigDeviceInfoActivity.start(this, deviceCode);
                        finish();
                        break;
                    case "sta":
                        final String stationCode = (String) jsonObject.get("stationCode");
                        final String stationName = (String) jsonObject.get("stationName");
                        handleStaDecode(stationCode, stationName);
                        break;
                }
            } else {
                ToastUtil.showToast("无效二维码");
                finish();
            }
        } catch (JSONException e) { //拼接字符串二维码解析
            Log.e("lwjing", "JSONException: ---->" + code);

            if (!code.contains("#&")){
               // ToastUtil.showToast("无效二维码");
                //finish();
                if (mode == MODE_BIND_WATER) {
                    bindWater(code);
                } else {
                    txtResult.setText((obj.getBarcodeFormat().toString() + ":" + obj.getText()));
                    Log.i(Tag, "条码为--->" + obj.getText() + "type:" + obj.getBarcodeFormat());
                    Log.e("xxxx", "handleDecode: " + code);
                    Intent intent = new Intent();
                    intent.putExtra("code", obj.getText());
                    intent.putExtra("type", obj.getBarcodeFormat().toString());
                    setResult(RESULT_OK, intent);
                    finish();
                }
                return;
            }
            final String[] strings = code.split("#&");
            Log.d(TAG, "handleDecode: ---->" + code);
            if (strings.length == 4 && strings[0].equals("HuaXinData")) {
                if (strings[1].equals("sta")) {

                    handleStaDecode(strings[2],strings[3]);
                } else if (strings[1].equals("dev")) {
                    BigDeviceInfoActivity.start(this, strings[2]);
                    finish();
                }

            } else {
                if (mode == MODE_BIND_WATER) {
                    bindWater(code);
                } else {
                    txtResult.setText((obj.getBarcodeFormat().toString() + ":" + obj.getText()));
                    Log.i(Tag, "条码为--->" + obj.getText() + "type:" + obj.getBarcodeFormat());
                    Log.e("xxxx", "handleDecode: " + code);
                    Intent intent = new Intent();
                    intent.putExtra("code", obj.getText());
                    intent.putExtra("type", obj.getBarcodeFormat().toString());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        }
    }

    /**
     * 站点二维码扫描
     * @param stationCode
     * @param stationName
     */
    private void handleStaDecode(final String stationCode, final String stationName) {
        if (mode == MODE_BIND_STATION) {
            Dialog dialog = DialogUtil.getConfirmDialog(ScanCaptureActivity.this, "扫描结果为" + stationCode + ",是否绑定？",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.putExtra(Constants.IK_STATION_NAME, stationName);
                            intent.putExtra(Constants.IK_STATION_CODE, stationCode);
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    },
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.sendEmptyMessage(R.id.restart_preview);
                        }
                    }).create();
            dialog.show();
        } else {
            //厂站签到
            HxStationSignInActivity.start(this,stationCode);
           // HxStationInfoActivity.start(this, stationCode);
            finish();
        }
    }


    private void bindCar(final String code) {
        Dialog dialog = DialogUtil.getConfirmDialog(this, "扫描结果为" + code + ",是否绑定？",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ApiAddVehicle(code);
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.sendEmptyMessage(R.id.restart_preview);

                    }
                }).create();

        dialog.setCancelable(false);
        dialog.show();

    }

    private void ApiAddVehicle(final String code) {

        final Dialog dialog = DialogUtil.getWaitDialog(this, "提交中");
        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().addVehicle(code, extraId);
        autoClose(call);
        call.enqueue(new retrofit2.Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                BaseDTO baseDTO = response.body();
                if (response.isSuccessful()) {
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        Intent intent = new Intent();
                        intent.putExtra(Constants.IK_PLATE_NUM, code);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                    } else {
                        ToastUtil.showToast(baseDTO.getMsg());
                        bindCar(code);
                    }
                } else {
                    ToastUtil.showToast("网络故障");
                    bindCar(code);
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
                bindCar(code);
            }
        });
    }

    private void ApiFindStation(String code) {
        Call<StationDTO> call = HxTransmitRequestHelper.getRequestApi().getStationInfo(code);
        autoClose(call);
        call.enqueue(new retrofit2.Callback<StationDTO>() {
            @Override
            public void onResponse(Call<StationDTO> call, Response<StationDTO> response) {
                final StationDTO station = response.body();
                if (response.isSuccessful()) {
                    if (station != null && station.isSuccessful()) {
                        Dialog dialog = DialogUtil.getConfirmDialog(ScanCaptureActivity.this, "扫描结果为" + station.getStationName() + ",是否绑定？",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Intent intent = new Intent();
                                        intent.putExtra(Constants.IK_STATION_CODE, station.getStationCode());
                                        intent.putExtra(Constants.IK_STATION_NAME, station.getStationName());
                                        setResult(RESULT_OK, intent);
                                        finish();
                                    }
                                },
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        handler.sendEmptyMessage(R.id.restart_preview);
                                    }
                                }).create();
                        dialog.show();
                    }
                }
            }

            @Override
            public void onFailure(Call<StationDTO> call, Throwable t) {

            }
        });

    }


    private void bindWater(final String code) {
        Dialog dialog = DialogUtil.getConfirmDialog(this, "扫描结果为" + code + ",是否绑定？",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ApiCommitWaterInLet(code);
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.sendEmptyMessage(R.id.restart_preview);
                    }
                }).create();

        dialog.show();
    }

    //    @Override
    //    public boolean onKeyDown(int keyCode, KeyEvent event) {
    //        // 手机返回按钮
    //        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    //            inactivityTimer.onActivity();
    //            Intent intent = new Intent();
    //            intent.putExtra("code", "");
    //            setResult(RESULT_OK, intent);
    //            CameraManager.get().closeDriver();
    //            finish();
    //            onDestroy();
    //            return false;
    //        } else {
    //            return super.onKeyDown(keyCode, event);
    //        }
    //    }

    // private void initBeepSound() {
    // if (playBeep && mediaPlayer == null) {
    // // The volume on STREAM_SYSTEM is not adjustable, and users found it
    // // too loud,
    // // so we now play on the music stream.
    // setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // mediaPlayer = new MediaPlayer();
    // mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    // mediaPlayer.setOnCompletionListener(beepListener);
    //
    // AssetFileDescriptor file = getResources().openRawResourceFd(
    // R.raw.beep);
    // try {
    // mediaPlayer.setDataSource(file.getFileDescriptor(),
    // file.getStartOffset(), file.getLength());
    // file.close();
    // mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
    // mediaPlayer.prepare();
    // } catch (IOException e) {
    // mediaPlayer = null;
    // }
    // }
    // }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onSensorChanged(SensorEvent event) {
        //not need to open flash light
        if (!CarPlateDetection.TEST) {
            return;
        }
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

        } else if (event.sensor.getType() == Sensor.TYPE_LIGHT) {
            float light = event.values[0];
            System.out.println("onSensorChanged(TYPE_LIGHT):" + light);
            if (light < (SensorManager.LIGHT_CLOUDY / 4)) {
                FlashlightManager.enableFlashlight();
                LigthOpen = true;
                //CameraManager.get().toast("打开闪光灯");
            } else {
                FlashlightManager.disableFlashlight();
                LigthOpen = false;
                //CameraManager.get().toast("关闭闪光灯");
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    public void ApiCommitWaterInLet(final String result) {
        final Dialog dialog = DialogUtil.getWaitDialog(this, "提交中");
        dialog.show();
        Call<WaterIntakeDTO> call = HxTransmitRequestHelper.getRequestApi().commitQrCode(extraId, result);
        autoClose(call);
        call.enqueue(new retrofit2.Callback<WaterIntakeDTO>() {
            @Override
            public void onResponse(Call<WaterIntakeDTO> call, Response<WaterIntakeDTO> response) {
                dialog.dismiss();
                WaterIntakeDTO waterIntake = response.body();
                if (response.isSuccessful()) {
                    if (waterIntake != null && waterIntake.isSuccessful()) {
                        waterIntake.setQrCode(result);
                        waterIntake.setIsFinish(1);
                        Intent intent = new Intent();
                        intent.putExtra(Constants.IK_WATER_INTAKE, waterIntake);
                        setResult(RESULT_OK, intent);
                        finish();
                    } else {
                        if (waterIntake != null){
                            ToastUtil.showToast(waterIntake.getMsg());
                        }else{
                            ToastUtil.showToast("绑定异常");
                        }
                    }
                } else {
                    ToastUtil.showToast("网络故障");
                }
            }

            @Override
            public void onFailure(Call<WaterIntakeDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
            }
        });
    }

}